import java.math.BigDecimal;
class Cheque {
        static transients = ['juros', 'valorLiquido']
        
	static constraints = {
		numero(blank:false)
		valor(nullable:false)
		emitente(nullable:false)
		dataEntrada(nullable:false)
		dataVencimento(nullable:false)
	}
	
	
	Emitente emitente
	String numero
	Double valor
	Calendar dataEntrada
	Calendar dataVencimento
	Operacao operacao
	
	
	public Double getJuros(){
		return calculaJuros(dataEntrada, dataVencimento, valor, operacao.fator)
	}
	
	public Double getValorLiquido(){
		//println 'valor -> ' + valor + ' juros -> ' + getJuros() + ' | ' + valor - getJuros()
		return (valor - getJuros())
	}
	
	
	public Double calculaJuros(Calendar dataInicio, Calendar dataFim,
			Double capital, Double taxaMes) {
		double periodos = 0;
		double juros = 0;

		List<Integer> diasDoMes = new ArrayList<Integer>();
		List<Integer> maxDiasMes = new ArrayList<Integer>();
		// int mesAtual = dataInicio.get(Calendar.MONTH);
		int diasCount = 1;
		while (dataInicio.before(dataFim)) {
			
			diasCount++;
			dataInicio.add(Calendar.DAY_OF_MONTH, 1);
			
			
			
			if (dataInicio.get(Calendar.DATE) == dataFim.get(Calendar.DATE)
					&& dataInicio.get(Calendar.MONTH) == dataFim.get(Calendar.MONTH)
					&& dataInicio.get(Calendar.YEAR) == dataFim.get(Calendar.YEAR)) {
				diasDoMes.add(--diasCount);
				maxDiasMes.add(dataInicio
						.getActualMaximum(Calendar.DAY_OF_MONTH));
				//System.out.println("Mes *- " + (dataInicio.get(Calendar.MONTH) + 1));
				
				diasCount = 0;
				
			} else if (dataInicio.get(Calendar.DAY_OF_MONTH) == dataInicio
					.getActualMaximum(Calendar.DAY_OF_MONTH)) {
				diasDoMes.add(diasCount);
				maxDiasMes.add(dataInicio
						.getActualMaximum(Calendar.DAY_OF_MONTH));
				//System.out.println("Mes - " + (dataInicio.get(Calendar.MONTH) + 1));
				diasCount = 0;
			}

		}
		int count = 0;
		for (Integer integer : maxDiasMes) {
			double res = new Double(diasDoMes.get(count).toString());
			double res2 = new Double(maxDiasMes.get(count).toString())
					.doubleValue();

			// per�odo (dias -> diasDoMes.get(count) / numero de dias
			// maxDiasMes.get(count)
			double res3 = res / res2;
			
			//System.out.println(res + "/" + res2); 

			periodos += res3;
			
			count++;
		}
		//System.out.println("Peridodos -> " + periodos);
		juros = round(Math.pow(1 + taxaMes / 100, round(periodos, 4)) - 1, 4);
		//System.out.println("JP -> " + juros);
		return round(capital * juros, 2);
	}

	private static double round(double d, int decimalPlace) {
		// see the Javadoc about why we use a String in the constructor
		// http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html#BigDecimal(double)
		BigDecimal bd = new BigDecimal(Double.toString(d));
		bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
		return bd.doubleValue();
	}
}
